package com.example.springlearn.service.impl;

import com.example.springlearn.bean.QuestionInfo;
import com.example.springlearn.mapper.QuestionMapper;
import com.example.springlearn.service.QuestionService;
import com.example.springlearn.util.StaticParamUtil;
import com.example.springlearn.util.redis.ListUtil;
import com.example.springlearn.util.redis.ToolsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class QuestionServiceImpl implements QuestionService {

    @Resource
    QuestionMapper questionMapper;

    @Resource
    ListUtil listUtil;

    @Resource
    ToolsUtil toolsUtil;


    @Override
    public void insertQue(QuestionInfo questionInfo) {
        questionMapper.insertQue(questionInfo);
    }

    @Override
    public void deleteQue(Integer qid) {
        questionMapper.deleteQue(qid);
    }

    @Override
    public void updateQue(QuestionInfo questionInfo) {
        questionMapper.updateQue(questionInfo);
    }

    @Override
    public List<QuestionInfo> queryAll() {
        boolean b = toolsUtil.hasKey(StaticParamUtil.ALL_QUESTIONS);
        if (b) {
            List<Object> objects = listUtil.lGet(StaticParamUtil.ALL_QUESTIONS, 0, -1);
            log.info("ALL_QUESTIONS load from redis");
            return new ArrayList<QuestionInfo>() {{
                for (Object object : objects) {
                    add((QuestionInfo) object);
                }
            }};
        }

        List<QuestionInfo> questionInfos = questionMapper.queryAll();
        listUtil.lSet(StaticParamUtil.ALL_QUESTIONS, questionInfos.toArray());
        return questionInfos;
    }

    @Override
    public QuestionInfo queryByQid(Integer qid) {
        return questionMapper.queryByQid(qid);
    }
}
